package com.woorigil.social.parser.coupang;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Elements;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.woorigil.social.DateUtils;
import com.woorigil.social.domain.ProviderCode;
import com.woorigil.social.domain.deal.Deal;
import com.woorigil.social.domain.deal.ManageStatus;

@Component
public class CoupangXmlShoppingParser {
	@Value("${coupang.shopping.path}")
	String dealPath;
	
	public List<Deal> parse() throws Exception {
		InputStream is = new FileInputStream(dealPath);
		Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		return parse(reader);
	}
	
	public String getValue(Element element) {
		return XmlHelper.getValue(element);
	}

	public List<Deal> parse(Reader reader) throws Exception {
		Builder builder = new Builder();
		Document doc = builder.build(reader);
		Element root = doc.getRootElement();

		String resultStatus = getValue(root.getFirstChildElement("result_status"));

		if (!"SUCCESS".equals(resultStatus)) {
			throw new IllegalStateException(getValue(root.getFirstChildElement("result_message")));
		}

		List<Deal> deals = new ArrayList<Deal>();
		
		Element dealsEle = root.getFirstChildElement("deals");
		Elements dealsEles = dealsEle.getChildElements();
		for (int i = 0; i < dealsEles.size(); i++) {
			Element dealEl = dealsEles.get(i);
			
			String category = getValue(dealEl.getFirstChildElement("category"));
			String section1 = getValue(dealEl.getFirstChildElement("section1"));
			
			if (isNotShoppingFreeCoupon(category, section1)) {
				continue;
			}
			
			Deal deal = new Deal();
			deal.setProviderCode(ProviderCode.CP);
			deal.setMetaId(getValue(dealEl.getFirstChildElement("meta_id")));
			deal.setCategory(category);
			deal.setSection1(section1);
			deal.setSection2(getValue(dealEl.getFirstChildElement("section2")));
			deal.setSection3(getValue(dealEl.getFirstChildElement("section3")));
			deal.setSaleStartAt(DateUtils.toDate(getValue(dealEl.getFirstChildElement("sale_start_at")), "yyyyMMddHHmmss"));
			deal.setSaleEndAt(DateUtils.toDate(getValue(dealEl.getFirstChildElement("sale_end_at")), "yyyyMMddHHmmss"));
			deal.setUseStartAt(getValue(dealEl.getFirstChildElement("use_start_at")));
			deal.setUseEndAt(getValue(dealEl.getFirstChildElement("use_end_at")));
			deal.setTitle(getValue(dealEl.getFirstChildElement("title")));
			deal.setWebLink(getValue(dealEl.getFirstChildElement("web_link")));
			deal.setMobileLink(getValue(dealEl.getFirstChildElement("mobile_link")));
			deal.setOriginalPrice(Integer.parseInt(getValue(dealEl.getFirstChildElement("original_price"))));
			deal.setSalesPrice(Integer.parseInt(getValue(dealEl.getFirstChildElement("sales_price"))));
			deal.setDiscountRate(Integer.parseInt(getValue(dealEl.getFirstChildElement("discount_rate"))));
			deal.setMaxCount(Integer.parseInt(getValue(dealEl.getFirstChildElement("max_number"))));
			deal.setMinCount(Integer.parseInt(getValue(dealEl.getFirstChildElement("min_number"))));
			deal.setNowCount(Integer.parseInt(getValue(dealEl.getFirstChildElement("now_number"))));
			deal.setSalesStatus(getValue(dealEl.getFirstChildElement("status")));

			Element imageEl = dealEl.getFirstChildElement("image");
			deal.setImageUrl1(getValue(imageEl.getFirstChildElement("web_top_url")));
			deal.setImageUrl2(getValue(imageEl.getFirstChildElement("web_recommend_url")));
			deal.setImageUrl7(getValue(imageEl.getFirstChildElement("mobile_thumbnail_url")));

			deal.setImageUrl(getValue(imageEl.getFirstChildElement("web_recommend_url")));
			deal.setAverageCount((int) (deal.getNowCount() / DateUtils.getTodayCount(deal.getSaleStartAt())));
			deal.setManageStatus(ManageStatus.S);
			deal.setCategoryId(12);
			deals.add(deal);
		}

		return deals;
	}

	private boolean isNotShoppingFreeCoupon(String category, String section1) {
		if (category == null || section1 == null) {
			return true;
		}
		
		if (!"쇼핑".equals(category)) {
			return true; 
		}
		
		if (section1.contains("할인권") || section1.contains("이용권")) {
			return false;
		}
		return true;
	}
}
